<?php
namespace app\index\controller;

use think\Controller;

use app\index\model\Member;
use app\index\model\OperateLog;
use app\index\model\PointLog;
use app\index\model\Coupon;
use app\index\model\Award;
use app\index\model\SendOrder;

class Index extends Controller
{
    private $size = 10; // 默认传递数据量

    public function initialize(){
        $this->size = config('app.page_num');
    }

    public function index()
    {
        if(session('?first')){
            session('first', null);
            $this->assign('first', true);
        }
        $ads = db('articles')->where('status', 1)->select();
        return view('/index', ['index' => true, 'ads'=>$ads]);
    }

    //帮助页
    public function help()
    {
        return view('/help', ['help' => true]);
    }

    //联系
    public function contact(){
        return view('/contact', ['help' => true]);
    }
    //投诉
    public function complain(){
        return view('/complain', ['help' => true]);
    }
    // 提交投诉内容
    public function sendMsg(){
        $info = input('post.');
        if(strlen($info['content']) > 300 || strlen($info['content']) == 0) {
            return json(mesg(-2, '字数有误'));
        }
        $txt = file_get_contents(env('root_path').'data/minganci.txt');
        // $content = iconv('gb2312', "utf-8", $txt);
        $words = explode(PHP_EOL, $txt);
        $regx = '/'. join('|', $words) .'/i';
        $res = preg_match($regx, $info['content'], $words);
        if($res){
            return json(mesg(-1, '内容包含敏感词汇，发布失败'));
        }
        // $badword1 = array_combine($words,array_fill(0,count($words),'**')); 
        // dump($badword1);
        // $info['content'] = strtr($info['content'], $badword1); 
        switch ($info['type']) {
            case 1:
                $content = $info['content'];
                break;
            case 2:
                $content = '快递公司：'.$info['company'].', 内容：'.$info['content'];
                break;
            case 3:
                $content = '客服工号：'.$info['num'].', 内容：'.$info['content'];
                break;
            case 4:
                $content = $info['content'];
                break;
            
            default:
                return json(mesg(-1, '错误，请与管理员联系'));
                break;
        }
        $param = [
            'uid'  => session('user.id'),
            'content'   => $content,
            'type'  => $info['type']
        ];
        try{
            db('complaint')->insert($param);
            return json(mesg(0, 'ok'));
        } catch(\Exception $e){
            throw $e;
        }
    }

    //钱包页
    public function wallet(){
        $info = Member::field('memb_balance, memb_is_truth')->where('memb_id',session('user.id'))->find();
        return view('wallet',['info' => $info]);
    }
    public function getBill(){
        $page = request()->get('page', 0);
        $logs = OperateLog::where('member_id', session('user.id'))
        ->order('create_time', 'desc')->limit($this->size * $page, $this->size)->select();
        return json($logs);
    }

    //积分页
    public function star(){
        $point = Member::where('memb_id',session('user.id'))->value('memb_point');
        return view('star', ['point' => $point]);
    }
    public function getStar(){
        $page = request()->get('page', 0);
        $logs = PointLog::where('member_id', session('user.id'))
        ->order('create_time', 'desc')->limit($this->size * $page, $this->size)->select();
        return json($logs);
    }

    // 券
    public function voucher(){
        return view('voucher', ['person'=>true]);
    }
    public function getVoucher(){
        $type = request()->param('status', 0);
        $page = request()->get('page', 0);
        $coups = db('award')->where('awar_uid', session('user.id'))->where('awar_status', $type)
        ->order('awar_id', 'desc')->limit($this->size * $page, $this->size)->select();
        return json($coups);
    }

    // 抽奖页
    public function lottery(){
        $memb = new Member;
        $count = $memb->getCount();
        return view('lottery', ['count'=>$count]);
    }
    public function getLottery(){
        $memb = Member::find(session('user.id'));
        if($memb->memb_count == 0) return json(mesg(-1, '抽奖次数不足'));
        $pro = [
            1 => ['prize'=>'免费寄件券', 'v'=>2],
            2 => ['prize'=>'免费手机贴膜', 'v'=>10],
            3 => ['prize'=>'3元寄件减免券', 'v'=>100],
            4 => ['prize'=>'电影票一张', 'v'=>1],
            5 => ['prize'=>'手机贴膜5折券', 'v'=>200],
            6 => ['prize'=>'2元余额红包', 'v'=>200],
            7 => ['prize'=>'驾校报名返现金200元', 'v'=>4743],
            8 => ['prize'=>'谢谢参与', 'v'=>4744],
        ];
        $id = $memb->getLottery($pro);
        if($id != 8){
            $param = [
                'awar_code' => randOrder('a'),
                'awar_name' => $pro[$id]['prize'],
                'awar_uid'  => session('user.id'),
            ];
            if($id == 6){
                Member::updateBalance(session('user.id'), 2, '抽奖');
                $param['awar_status'] = 1;
            }
            db('award')->insert($param);
        }
        foreach ($pro as $k => $v){
            unset($pro[$k]['v']);
        }
        return json(mesg(0, $pro[$id]['prize'], ['prize'=>$pro, 'count'=>$memb->memb_count]));
    }

    //获得中奖者信息
    public function getAward(){
        $award = new Award();
        $data = $award->getAward([['awar_name', '<>', '驾校报名返现金200元']], 30);
        $other = $award->getAward([], 50 - count($data));
        foreach ($other as $v) {
            $data[] = $v;
        }
        return json(mesg(0, 'ok', $data));
    }
    


    //修改密码
    public function updatePwd(){
        $phone = request()->post('phone');
        $captcha = request()->post('captcha');
        $pwd = request()->post('new_pwd');
        if(!empty($captcha) && !empty($pwd)){
            if($captcha != cache('captcha')){
                return json(mesg(-1, '验证码不正确'));
            }
            $res = Member::where('memb_phone', $phone)->update(['memb_password'=>password_hash($pwd, PASSWORD_DEFAULT)]);
            if($res > 0) {
                return json(mesg(0, '修改成功'));
            }else{
                return json([
                    'code' => '-2',
                    'msg'    => '未知错误',
                ], 302);
            }
        }
    }

    // 更新顾客收运订单
    public function updateSendorder(){
        try {
            SendOrder::whereTime('get_time', '<=', '-24 hours')->where('send_status', 1)->update([
                'send_status' => 2,
            ]);
            return 'ok';
        } catch (\Throwable $th) {
            //throw $th;
        }
    }
}
